import axios, { AxiosRequestConfig, InternalAxiosRequestConfig, AxiosResponse } from 'axios';

// 定义扩展请求配置接口
interface IRequestConfig extends AxiosRequestConfig {
  apiLoading?: string;
}

// 定义响应数据接口
interface IResponseData {
  code: number;
  data: unknown;
  message?: string;
}

// 创建 Axios 实例
const server = axios.create({
  timeout: 300000,
  headers: {
    Authorization: 'Bearer pat_dApsPsRFsqTeaijdIxRi8jYvV96Ud4Du9aj5ah0PszihF8yLfoEozXJpr3RMn4Yl',
  },
});

/**
 * 请求拦截器
 */
server.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    if (localStorage.getItem('token')) {
      config.headers = config.headers || {};
      config.headers.Authorization = `Bearer ${localStorage.getItem('token')}`;
    }
    return config;
  },
  (err) => {
    if (axios.isCancel(err)) {
      console.log('取消本次请求', err.message);
      return Promise.reject(err);
    } else {
      return Promise.reject(err);
    }
  }
);

/**
 * 响应拦截器
 */
server.interceptors.response.use(
  (res) => {
    console.log(res);
    // 对结果数据进行操作
    return res;
  },
  (err) => {
    // 接口处理错误
    return Promise.reject(err);
  }
);

// 定义 API 接口
export interface IApi {
  request(config: IRequestConfig): Promise<IResponseData>;
  get(url: string, data?: Record<string, unknown>, config?: IRequestConfig): Promise<IResponseData>;
  post(url: string, data?: Record<string, unknown>, config?: IRequestConfig): Promise<IResponseData>;
}

// 判断是否为移动端设备
const isMobile = function (): boolean {
  const userAgent = navigator.userAgent.toLowerCase();
  return /iphone|ipod|android|windows phone|blackberry|bb10|mobi|xoom|tablet|mobile/i.test(userAgent);
};

// 实现 API 接口
const api: IApi = {
  request(config: IRequestConfig) {
    return new Promise<IResponseData>((resolve, reject) => {
      server.request(config)
        .then((res: AxiosResponse<IResponseData>) => {
          /**
           * @param {status -> code}
           * 200: 请求成功
           */
          if (res.status === 200) {
            if (res.data.code === 401) {
              if (isMobile()) {
                if (process.env.NODE_ENV === 'development') {
                  // location.href = `${process.env.VUE_APP_BASE_API}AI/wechatApi/authorize`;
                } else if (process.env.NODE_ENV === 'test') {
                  location.href = `${process.env.VUE_APP_BASE_API}AIBackend/Api/wechatApi/authorize`;
                } else {
                  location.href = `${process.env.VUE_APP_BASE_API}AIBackend/Api/wechatApi/authorize`;
                }
              } else {
                if (process.env.NODE_ENV === 'development') {
                  // location.href = `${process.env.VUE_APP_BASE_API}AI/wechatApi/authorizeAAD`;
                } else if (process.env.NODE_ENV === 'test') {
                  location.href = `${process.env.VUE_APP_BASE_API}AIBackend/Api/wechatApi/authorizeAAD`;
                } else {
                  location.href = `${process.env.VUE_APP_BASE_API}AIBackend/Api/wechatApi/authorizeAAD`;
                }
              }
              console.log('token过期');
              return;
            } else {
              resolve(res.data);
            }
          } else {
            reject(res);
          }
        })
        .catch((e) => {
          reject(e);
        });
    });
  },

  get(url: string, data?: Record<string, unknown>, config?: IRequestConfig) {
    const requestConfig: IRequestConfig = {
      method: 'GET',
      url,
      params: data,
      ...config,
    };
    return new Promise<IResponseData>((resolve, reject) => {
      this.request(requestConfig)
        .then((res: IResponseData) => {
          resolve(res);
        })
        .catch((e: Error) => {
          reject(e);
        });
    });
  },

  post(url: string, data?: Record<string, unknown>, config?: IRequestConfig) {
    const requestConfig: IRequestConfig = {
      method: 'POST',
      url,
      data,
      ...config,
    };
    return new Promise<IResponseData>((resolve, reject) => {
      this.request(requestConfig)
        .then((res: IResponseData) => {
          resolve(res);
        })
        .catch((e: Error) => {
          reject(e);
        });
    });
  },
};

export default api;